#include "widget.h"
#include "ui_widget.h"

#include <QFile>
#include <QTextStream>
#include <QSystemTrayIcon>
#include <QMenu>
#include <QAction>
#include <QApplication>

#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>

#include <QFileDialog>
#include <algorithm>

#include <QFile>
#include <cstdio>



Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    setWindowIcon(QIcon(":/main/icon.png"));
    player = new QMediaPlayer();
    settings = new QSettings("LxSoft","BellSystem");

    model = new QStandardItemModel;
//    QStandardItem* item = new QStandardItem("123");
//    model->appendRow(item);
    restoreSettings();

    ui->listView->setModel(model);


//    initTray();


    timer = new QTimer(this);
    connect(timer,&QTimer::timeout, this, &Widget::testTime);
    timer->start(1000);


}

Widget::~Widget()
{
    delete ui;
}


void Widget::closeEvent(QCloseEvent *event)
{
    event->accept();
    return;
    if(!event->spontaneous()){
        event->accept();
        return;
    }
    this->hide();
    tray->show();

    event->ignore();
}




void Widget::initTray()
{

    tray = new QSystemTrayIcon(this);
    tray->hide();
    tray->setIcon(QIcon(":/main/icon.png"));
    tray->setToolTip("打铃系统 v1.0");
    QMenu *menu = new QMenu(this);
    QAction *closeAction = new QAction(this);
    closeAction->setText("退出程序");
    connect(closeAction,&QAction::triggered,this,&Widget::close);
    menu->addAction(closeAction);
    tray->setContextMenu(menu);
    connect(tray, &QSystemTrayIcon::activated ,this,&Widget::trayIconAction);
}

void Widget::restoreSettings()
{
    mediaName = settings->value("mediaName").value<QString>();
    player->setMedia(QUrl(mediaName));
    ui->mediaFileEdit->setText(mediaName);



    QFile file(QCoreApplication::applicationDirPath()+"/time.ini");
    if(!file.open(QIODevice::ReadOnly|QIODevice::Text)){
//        qDebug()<<QCoreApplication::applicationDirPath()+"/time.ini";
        qDebug()<<file.errorString();
        return;
    }
    char buffer[1024];
    int h,m,s;
    int enabled;
    while(file.readLine(buffer,1024)>0){
        sscanf(buffer,"%d%d%d%d",&h,&m,&s,&enabled);
        events.push_back({QTime(h,m,s),(bool)enabled});
    }
    int size = events.size();
    for (int i = 0; i < size; ++i) {
        qDebug()<<events[i].time.toString("hh:mm:ss");
        QStandardItem *item = new QStandardItem(events[i].time.toString("hh:mm:ss"));
        if(!events[i].enabled)item->setForeground(QBrush(QColor(100,100,100)));
        model->appendRow(item);
    }
}


void Widget::saveEvents()
{
    QFile file(QCoreApplication::applicationDirPath()+"/time.ini");
    file.open(QIODevice::WriteOnly|QIODevice::Text);
    char buffer[1024];
    for(auto x:events){
        memset(buffer,0,sizeof(buffer));
        sprintf(buffer,"%d %d %d %d\n",x.time.hour(),x.time.minute(),x.time.second(),x.enabled);
        file.write(buffer,strlen(buffer));
    }
}

QTime Widget::getTime()
{
    auto s = ui->lineEdit->text();
    int hour,minute,second=0;
//    qDebug()<<s;
    auto sl = s.split(' ');
    if(sl.size()<2 || sl.size()>3){
        return QTime(-1,-1,-1);
    }
    hour = sl[0].toInt();
    minute = sl[1].toInt();
    if(sl.size()==3){
        second = sl[2].toInt();
    }
//    qDebug()<<hour<<minute<<second;
    return QTime(hour,minute,second);
}

void Widget::trayIconAction(QSystemTrayIcon::ActivationReason reason)
{
    if(reason == QSystemTrayIcon::Trigger){
        this->show();
        tray->hide();
    }
}


void Widget::ringBell()
{
    qDebug()<<"Ring";
    if(player->state()==QMediaPlayer::StoppedState && player->isAudioAvailable()){
        player->play();
    }
}

void Widget::testTime()
{
//    qDebug()<<events;
//    qDebug()<<player->mediaStatus()<<player->isAudioAvailable();
    int n = events.length();

//    qDebug() << "testTime a "<<n;
    for(int i=0;i<n;i++){
        if(!events[i].enabled)continue;
//        qDebug() << "testTime  "<<i;
        int secTo = events[i].time.secsTo(QTime::currentTime());
        if( secTo>=0 && secTo< 5 ){
            ringBell();
        }
    }
}


void Widget::onLoadMedia()
{
    mediaName = QFileDialog::getOpenFileName(this,"选择铃声","C:\\");
    player->setMedia(QUrl(mediaName));
    ui->mediaFileEdit->setText(mediaName);
    settings->setValue("mediaName",mediaName);

}

void Widget::onAddEvent()
{

    QTime t = getTime();
    ui->lineEdit->clear();
    if(!t.isValid()){
        return;
    }
    auto pos = std::lower_bound(events.begin(),events.end(),t) - events.begin();

    events.insert(pos,{t,1});
//    qDebug()<<events;

    saveEvents();
    QStandardItem *item = new QStandardItem(t.toString("hh:mm:ss"));
    model->insertRow(pos,item);
}

void Widget::onRemoveEvent()
{
    if(ui->listView->currentIndex().row()<0)return;
//    qDebug()<<ui->listView->currentIndex();
    events.remove(ui->listView->currentIndex().row());
    saveEvents();
    model->removeRow(ui->listView->currentIndex().row());
}

void Widget::onDisableEvent()
{
    if(ui->listView->currentIndex().row()<0)return;
    bool &e = events[ui->listView->currentIndex().row()].enabled;
    QStandardItem* item = model->item(ui->listView->currentIndex().row());
        if(e){
            item->setForeground(QBrush(QColor(100,100,100)));
    }else{
        item->setForeground(QBrush(QColor(0,0,0)));
    }
    e=!e;
//    qDebug()<<events[ui->listView->currentIndex().row()].enabled;
    saveEvents();
}



bool BellEvent::operator<(const BellEvent &o)const
{
    return time<o.time;
}

bool BellEvent::operator<(const QTime &o)const
{
    return  time<o;
}
